package com.archstoday.activity;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.archstoday.BaseApp;
import com.archstoday.R;
import com.archstoday.adapter.CommentForTopicAdapter;
import com.archstoday.common.AsRes;
import com.archstoday.common.SpfUtils;
import com.archstoday.entity.BaseEntity;
import com.archstoday.entity.CommentCommitEntity;
import com.archstoday.entity.EngineesDetailsEntity;
import com.archstoday.entity.NewsDetailsEntity;
import com.archstoday.entity.ShareEntity;
import com.archstoday.entity.TopicDetailComentEntity;
import com.archstoday.event.MessageRefreshNewsEvent;
import com.archstoday.utils.KeybordUtil;
import com.archstoday.utils.OAuthUtils;
import com.archstoday.utils.PdfURLUtils;
import com.archstoday.utils.ProcessUtils;
import com.archstoday.utils.RxTimeUtils;
import com.archstoday.utils.ToolUtils;
import com.archstoday.utils.WechatUtils;
import com.archstoday.view.MyListView;
import com.archstoday.view.PullScrollView;
import com.archstoday.view.PullToRefreshLayout;
import com.base.http.common.BaseHttpClient;
import com.base.utils.ImageUtil;
import com.base.utils.MySharedPreferencesMgr;
import com.base.utils.StringUtil;
import com.bumptech.glide.Glide;
import com.gifdialog.DialogUtil;
import com.gifdialog.GifDialog;
import com.shuyu.action.web.ActionSelectListener;
import com.shuyu.action.web.CustomActionWebView;
import com.tools.app.view.RationImageView;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * 话题详情页面
 */
public class TopsDetailsActivity extends AsScrollBaseActivity implements PullToRefreshLayout.OnRefreshListener, CommentForTopicAdapter.onReplyListener {

    private TextView mTitleTv, mCommentTv;
    private TextView mDetailsTitleTv, mFromeTv, mDesTv;
    private CustomActionWebView mWebView;
    private RationImageView mTopImageView;
    private TextView mSubscribeBtn;

    private TextView mTopicDetailComment;

    private ImageView mHeaderImageView;
    private TextView mNameTitle;
    private TextView mNameDesc;
    private TextView mFocus;

    private int articleID;
    private String mChannel;

    private NewsDetailsEntity mNewsEntity;
    private EngineesDetailsEntity mEgEntity;
    private TopicDetailComentEntity mTopicDetailComentEntity;
    private String mAction;
    private String mFocusAction;

    List<String> list;

    //评论信息
    private PullToRefreshLayout mPullLayout;
    private MyListView mPullList;
    private PullScrollView mPullScroll;

    private CommentForTopicAdapter mCommentForTopicAdapter;
    private int page;
    private GifDialog loadingDialog;

    private String action;

    @Override
    protected void initView(Bundle bundle) {
        setContentView(R.layout.activity_tops_details);
        mTitleTv = (TextView) findViewById(R.id.title_tv);
        mCommentTv = (TextView) findViewById(R.id.right_tv);
        mDetailsTitleTv = (TextView) findViewById(R.id.details_title_tv);
        mFromeTv = (TextView) findViewById(R.id.details_from_tv);
        mDesTv = (TextView) findViewById(R.id.details_des_tv);
        mWebView = (CustomActionWebView) findViewById(R.id.details_content_view);

        mTopImageView = (RationImageView) findViewById(R.id.id_for_image_show);
        mSubscribeBtn = (TextView) findViewById(R.id.id_for_subscribe);

        mNameTitle = (TextView) findViewById(R.id.details_from_tv);
        mNameDesc = (TextView) findViewById(R.id.details_des_tv);
        mFocus = (TextView) findViewById(R.id.id_for_focus);
        mHeaderImageView = (ImageView) findViewById(R.id.scheme_user_icon);

        mTopicDetailComment = (TextView) findViewById(R.id.id_for_topic_detail_comment);

        mPullLayout = (PullToRefreshLayout) findViewById(R.id.pull_layout);
        mPullList = (MyListView) findViewById(R.id.pull_list);
        mPullScroll = (PullScrollView) findViewById(R.id.pull_scroll);
        mPullLayout.setOnRefreshListener(this);
        mPullScroll.setPullDownEnable(false);
    }

    @Override
    protected void initData(Bundle bundle) {
        list = new ArrayList<>();
        list.add("拷贝");
        list.add("分享文字");

        initSetting();

        mTitleTv.setText("话题详情");
        articleID = getIntent().getIntExtra("id", 0);
        upNewsData();

        mCommentForTopicAdapter = new CommentForTopicAdapter(mContext);
        mCommentForTopicAdapter.setListener(this);
        mPullList.setAdapter(mCommentForTopicAdapter);

        page = 1;
    }

    private void initSetting() {
        mWebView.setWebViewClient(new CustomWebViewClient());

        //设置item
        mWebView.setActionList(list);

        //链接js注入接口，使能选中返回数据
        mWebView.linkJSInterface();

        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setDisplayZoomControls(false);
        //使用javascript
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setDomStorageEnabled(true);

        //增加点击回调
        mWebView.setActionSelectListener(new ActionSelectListener() {

            @Override
            public void onClick(String title, String selectText) {
                Log.e("onClick", "onClick--");

                if (title.equalsIgnoreCase("分享文字")) {
                    Intent intent = new Intent();
                    intent.putExtra("id", articleID);
                    intent.putExtra("content", selectText);
                    intent.putExtra("type", "news");
                    intent.putExtra("categoryId1", mNewsEntity.getData().getCategoryId1());

                    intent.setClass(mContext, TextShareActivity.class);
                    startActivity(intent);
                }

                if (title.equalsIgnoreCase("拷贝")) {
                    ToolUtils.copyUrl(mContext, selectText);
                }
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mWebView != null) {
            mWebView.dismissAction();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    TopicDetailComentEntity.DataModelXX.CommentsModel.DataModel commitatPerson;

    @Override
    protected void initListener() {
        setOnClickListener(R.id.back_btn);
        setOnClickListener(R.id.details_share_btn);
        setOnClickListener(R.id.id_for_focus);
        setOnClickListener(R.id.id_for_topic_detail_comment);
        setOnClickListener(R.id.id_for_subscribe);

        mPullList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.e("onItemClick", "onItemClick");

                commitatPerson = mCommentForTopicAdapter.getItem(position);
                //mTopicDetailComment.setText("@" + ProcessUtils.procesText(commitatPerson.getComment().getUserName()));

                show(null, commitatPerson);
            }
        });
    }

    @Override
    public void treatClickEvent(int id) {
        switch (id) {
            case R.id.back_btn:
                appFinish();
                break;
            case R.id.details_btn:
                getEvent(mApp.E_READ, mApp.PAGE_TYPE_READ);
                if (!StringUtil.isEmpty(mEgEntity.getData().getPdfAttachment())) {
                    if (ToolUtils.isPermission(mContext)) {
                        String pdfAddress = mEgEntity.getData().getPdfAttachment();
                        if (pdfAddress.indexOf(",") > 0) {
                            if (pdfAddress.indexOf("[") == 0) {
                                pdfAddress = pdfAddress.substring(pdfAddress.indexOf("[") + 1, pdfAddress.indexOf(","));
                            } else {
                                pdfAddress = pdfAddress.substring(0, pdfAddress.indexOf(","));
                            }
                        } else {
                            if (pdfAddress.indexOf("[") == 0) {
                                pdfAddress = pdfAddress.substring(pdfAddress.indexOf("[") + 1, pdfAddress.indexOf("]"));
                            }
                        }

                        Intent intent = new Intent(mContext, DownloadPdfActivity.class);
                        intent.putExtra("url", PdfURLUtils.getInstance().getPdf_url()
                                + pdfAddress);
                        startActivity(intent);
                    } else {
                        ToolUtils.getAppDetailSettingIntent(mContext);
                    }

                }
                break;
            case R.id.details_share_btn:
                setDialog();
                break;
            case R.id.share_wx_btn:
                Map<String, String> info = new HashMap<>();
                info.put("articleId", String.valueOf(mNewsEntity.getData().getArticleId()));
                info.put("categoryId1", String.valueOf(mNewsEntity.getData().getCategoryId1()));
                info.put("channel", "wechat");
                getEvent(BaseApp.E_DETAILS_SHARE, BaseApp.PAGE_TYPE_DETAILS_SHARE,
                        ToolUtils.mapToJson(info));

                mChannel = "wechat";
                share();
                break;
            case R.id.share_group_btn:
                info = new HashMap<>();
                info.put("articleId", String.valueOf(mNewsEntity.getData().getArticleId()));
                info.put("categoryId1", String.valueOf(mNewsEntity.getData().getCategoryId1()));
                info.put("channel", "friends");
                getEvent(BaseApp.E_DETAILS_SHARE, BaseApp.PAGE_TYPE_DETAILS_SHARE,
                        ToolUtils.mapToJson(info));

                mChannel = "friends";
                share();
                break;

            case R.id.share_link_btn:
                info = new HashMap<>();
                info.put("articleId", String.valueOf(mNewsEntity.getData().getArticleId()));
                info.put("categoryId1", String.valueOf(mNewsEntity.getData().getCategoryId1()));
                info.put("channel", "link");
                getEvent(BaseApp.E_DETAILS_SHARE, BaseApp.PAGE_TYPE_DETAILS_SHARE,
                        ToolUtils.mapToJson(info));

                mChannel = "msg";
                share();
                break;

            case R.id.id_for_focus:
                if (StringUtil.isEmpty(MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""))) {
                    showToast(R.string.user_userid_null);

                    Intent loginIntent = new Intent(mContext, LoginActivity.class);
                    startActivity(loginIntent);
                    appFinish();
                } else {
                    if (mNewsEntity == null) {
                        return;
                    }

                    if (mNewsEntity.getData().getIsArticleUserLiked() == 1) {
                        mFocusAction = "del";
                        focus();
                    } else {
                        mFocusAction = "add";
                        focus();
                    }
                }
                break;

            case R.id.id_for_topic_detail_comment:
                show(null, commitatPerson);
                break;
            case R.id.id_for_subscribe:
                if (StringUtil.isEmpty(MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""))) {
                    showToast(R.string.user_userid_null);

                    Intent loginIntent = new Intent(mContext, LoginActivity.class);
                    startActivity(loginIntent);
                    appFinish();
                } else {
                    if (mNewsEntity == null) {
                        return;
                    }
                    info = new HashMap<>();
                    info.put("articleId", String.valueOf(mNewsEntity.getData().getArticleId()));
                    info.put("categoryId1", String.valueOf(mNewsEntity.getData().getCategoryId1()));
                    getEvent(BaseApp.E_SUBSCIBE, BaseApp.PAGE_TYPE_SUBSCIBE,
                            ToolUtils.mapToJson(info));

                    if (mNewsEntity.getData().getIsSubscribe() == 1) {
                        action = "del";
                        subscribe();
                    } else {
                        action = "add";
                        subscribe();
                    }
                }
                break;
        }
    }

    private void focus() {
        initParameter();
        mParams.put("userIdLiked", mNewsEntity.getData().getUserId());
        mParams.put("userId", MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""));
        mParams.put("token", MySharedPreferencesMgr.getString(SpfUtils.USER_TOKEN, ""));
        mParams.put("plat", "android");
        mParams.put("ifa", mApp.getDeviceID(mContext));
        mParams.put("action", mFocusAction);

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.FOCUS_AUTHOR),
                AsRes.FOCUS_AUTHOR, mParams, BaseEntity.class);
    }

    private void upNewsData() {
        initParameter();
        mParams.put("id", articleID);
        mParams.put("userId", MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""));
        mParams.put("toke", MySharedPreferencesMgr.getString(SpfUtils.USER_TOKEN, ""));

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.GET_NEWS_DETAILS),
                AsRes.GET_NEWS_DETAILS, mParams, NewsDetailsEntity.class);
    }

    private void upEgData() {
        initParameter();
        mParams.put("id", articleID);

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.GET_ENGINEER_DETAILS),
                AsRes.GET_ENGINEER_DETAILS, mParams, EngineesDetailsEntity.class);
    }

    private void share() {
        initParameter();
        mParams.put("articleID", articleID);
        mParams.put("channel", mChannel);
        mParams.put("type", "news");

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.SHARE),
                AsRes.SHARE, mParams, ShareEntity.class);
    }

    private void subscribe() {
        initParameter();
        mParams.put("articleId", mNewsEntity.getData().getArticleId());
        mParams.put("categoryId1", mNewsEntity.getData().getCategoryId1());
        mParams.put("userId", MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""));
        mParams.put("token",MySharedPreferencesMgr.getString(SpfUtils.USER_TOKEN, "") );
        mParams.put("plat", "android");
        mParams.put("ifa", mApp.getDeviceID(mContext));
        mParams.put("action", action);

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.ARTICLE_SUBSCRIBE),
                AsRes.ARTICLE_SUBSCRIBE, mParams, BaseEntity.class);
    }

    @Override
    protected void onSuccess(String content, BaseHttpClient client, Object parse) {
        mPullLayout.refreshFinish(true);
        mPullLayout.loadMoreFinish(true);
        if (client.getUrlIdentifier() == AsRes.GET_NEWS_DETAILS) {
            mNewsEntity = (NewsDetailsEntity) parse;
            if (ToolUtils.isSuccess(mNewsEntity.getStatus())) {
                mCommentTv.setText(mNewsEntity.getData().getComments() + "条评论");
                if (mNewsEntity.getData().getIsSubscribe() == 0) {
                    mSubscribeBtn.setText("订阅");
                    mSubscribeBtn.setTextColor(mContext.getResources().getColor(R.color.white));
                    mSubscribeBtn.setBackgroundColor(mContext.getResources().getColor(R.color.green_text));
                } else {
                    mSubscribeBtn.setText("已订阅");
                    mSubscribeBtn.setTextColor(mContext.getResources().getColor(R.color.black));
                    mSubscribeBtn.setBackground(mContext.getResources().getDrawable(R.drawable.topic_has_focus));
                }

                mDetailsTitleTv.setText(mNewsEntity.getData().getTitle());
                mFromeTv.setText(mNewsEntity.getData().getUserName());
                mDesTv.setText(mNewsEntity.getData().getCreateTime());

                SimpleDateFormat DEFAULT_SDF = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
                String time = mNewsEntity.getData().getUploadTime();
                time = RxTimeUtils.milliseconds2String(RxTimeUtils.string2Milliseconds(time), DEFAULT_SDF);

                mNameDesc.setText(ProcessUtils.procesText(time));
                mNameTitle.setText(mNewsEntity.getData().getUserName());

//                mFocus.setVisibility(View.VISIBLE);
//                int focus = mNewsEntity.getData().getIsArticleUserLiked();
//                if (focus == 0) {
//                    mFocus.setText("关注");
//                    mFocus.setTextColor(mContext.getResources().getColor(R.color.white));
//                    mFocus.setBackgroundColor(mContext.getResources().getColor(R.color.green_text));
//                } else {
//                    mFocus.setText("已关注");
//                    mFocus.setTextColor(mContext.getResources().getColor(R.color.black));
//                    mFocus.setBackground(mContext.getResources().getDrawable(R.drawable.topic_has_focus));
//                }

                Glide.with(mContext).load(mNewsEntity.getData().getImgs())
                        .placeholder(R.mipmap.icon_backgroud)
                        .error(R.mipmap.icon_backgroud)
                        .into(mTopImageView);

                mHeaderImageView.setVisibility(View.VISIBLE);
                Glide.with(mContext).load(mNewsEntity.getData().getUserImg())
                        .placeholder(R.mipmap.user_header_icon)
                        .error(R.mipmap.user_header_icon)
                        .into(mHeaderImageView);

                if (StringUtil.equest("3", mNewsEntity.getData().getType())) {
                    mWebView.loadUrl(mNewsEntity.getData().getSourceDetailLink());
                } else {
                    mWebView.loadDataWithBaseURL(null,
                            mNewsEntity.getData().getContent(), "text/html", "utf-8", null);
                }

                //只有成功后 才进行评论的加载
                getCommentData();

            } else {
                showToast(mNewsEntity.getMsg());
            }
        } else if (client.getUrlIdentifier() == AsRes.GET_ENGINEER_DETAILS) {
            mEgEntity = (EngineesDetailsEntity) parse;
            if (ToolUtils.isSuccess(mEgEntity.getStatus())) {
                mDetailsTitleTv.setText(mEgEntity.getData().getTitle());
                mFromeTv.setText(mEgEntity.getData().getReleaseOrg());
                if (!StringUtil.isEmpty(mEgEntity.getData().getIndexNo())) {
                    mDesTv.setText("编号:" + mEgEntity.getData().getIndexNo());
                }
                mWebView.loadDataWithBaseURL(null,
                        mEgEntity.getData().getContent(), "text/html", "utf-8", null);
            } else {
                showToast(mEgEntity.getMsg());
            }
        } else if (client.getUrlIdentifier() == AsRes.SHARE) {
            ShareEntity entity = (ShareEntity) parse;
            if (ToolUtils.isSuccess(entity.getStatus())) {
                getEvent(mApp.E_SHARE, mApp.PAGE_TYPE_SHARE);
                switch (mChannel) {
                    case "wechat":
                        WechatUtils.share(mContext, entity.getData().getTitel(),
                                entity.getData().getDesp(), entity.getData().getUrl(),
                                false);
                        break;
                    case "friends":
                        WechatUtils.share(mContext, entity.getData().getTitel(),
                                entity.getData().getDesp(), entity.getData().getUrl(),
                                true);
                        break;
                    case "msg":
                        ToolUtils.copyUrl(mContext, entity.getData().getUrl());
                        break;
                }
                dismissShare();
            } else {
                showToast(entity.getMsg());
            }
        } else if (client.getUrlIdentifier() == AsRes.FOCUS_AUTHOR) {
            BaseEntity entity = (BaseEntity) parse;
            if (ToolUtils.isSuccess(entity.getStatus())) {
                switch (mFocusAction) {
                    case "add":
                        mFocus.setText("已关注");
                        mFocus.setTextColor(mContext.getResources().getColor(R.color.black));
                        mFocus.setBackground(mContext.getResources().getDrawable(R.drawable.topic_has_focus));

                        mNewsEntity.getData().setIsArticleUserLiked(1);
                        break;
                    case "del":
                        mFocus.setText("关注");
                        mFocus.setTextColor(mContext.getResources().getColor(R.color.white));
                        mFocus.setBackgroundColor(mContext.getResources().getColor(R.color.green_text));

                        mNewsEntity.getData().setIsArticleUserLiked(0);
                        break;
                }
            } else if (entity.getStatus() == 10005) {
                MySharedPreferencesMgr.setString(SpfUtils.USER_ID, "");
                MySharedPreferencesMgr.setString(SpfUtils.USER_TOKEN, "");
                OAuthUtils.getInstance().cleanUserInfo();

                showToast("登录信息已过期，请重新登录");
                Intent intent = new Intent(mContext, LoginActivity.class);
                startActivity(intent);
            } else {
                showToast(entity.getMsg());
            }
        } else if (client.getUrlIdentifier() == AsRes.TOPIC_DETAIL_COMMENT) {
            mTopicDetailComentEntity = (TopicDetailComentEntity) parse;

            if (ToolUtils.isSuccess(mTopicDetailComentEntity.getStatus())) {
                if (mTopicDetailComentEntity.getData() == null) {
                    return;
                }

                TopicDetailComentEntity.DataModelXX.CommentsModel entity = mTopicDetailComentEntity.getData().getComments();

                if (entity.getData() != null && entity.getData().size() > 0) {
                    if (page == 1) {
                        mCommentForTopicAdapter.setData(entity.getData());
                    } else {
                        mCommentForTopicAdapter.addData(entity.getData());
                        mPullScroll.scrollTo(mPullScroll.getScrollX(),
                                mPullScroll.getScrollY() - 10);
                    }
                    page++;
                }
            }

            if (loadingDialog != null) {
                loadingDialog.dismiss();
            }
        } else if (client.getUrlIdentifier() == AsRes.TOPIC_COMMIT_COMMENT) {
            CommentCommitEntity mCommentCommitEntity = (CommentCommitEntity) parse;

            if (ToolUtils.isSuccess(mCommentCommitEntity.getStatus())) {
                Toast.makeText(mContext, "发布成功~~~", Toast.LENGTH_SHORT).show();

                EventBus.getDefault().post(new MessageRefreshNewsEvent());

                //刷新评论列表
                //只有成功后 才进行评论的加载
                page = 1;
                getCommentData();
            } else if (mCommentCommitEntity.getStatus() == 10005) {
                MySharedPreferencesMgr.setString(SpfUtils.USER_ID, "");
                MySharedPreferencesMgr.setString(SpfUtils.USER_TOKEN, "");
                OAuthUtils.getInstance().cleanUserInfo();

                showToast("登录信息已过期，请重新登录");
                Intent intent = new Intent(mContext, LoginActivity.class);
                startActivity(intent);
            } else {
                if (loadingDialog != null) {
                    loadingDialog.dismiss();
                }

                Toast.makeText(mContext, mCommentCommitEntity.getMsg(), Toast.LENGTH_SHORT).show();
            }
        } else if (client.getUrlIdentifier() == AsRes.ARTICLE_SUBSCRIBE) {
            BaseEntity entity = (BaseEntity) parse;
            if (ToolUtils.isSuccess(entity.getStatus())) {
                switch (action) {
                    case "add":
                        mSubscribeBtn.setText("已订阅");
                        mSubscribeBtn.setTextColor(ImageUtil.getColor(mContext, R.color.black));
                        mSubscribeBtn.setBackgroundResource(R.drawable.topic_has_focus);

                        mNewsEntity.getData().setIsSubscribe(1);
                        break;
                    case "del":
                        mSubscribeBtn.setText("订阅");
                        mSubscribeBtn.setTextColor(ImageUtil.getColor(mContext, R.color.white));
                        mSubscribeBtn.setBackgroundResource(R.color.green_text);

                        mNewsEntity.getData().setIsSubscribe(0);
                        break;
                }
            } else {
                showToast(entity.getMsg());
            }
        }
    }

    @Override
    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
        page = 1;
        getCommentData();
    }

    @Override
    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
        getCommentData();
    }

    @Override
    public void reply(TopicDetailComentEntity.DataModelXX.CommentsModel.DataModel data, TopicDetailComentEntity.DataModelXX.CommentsModel.DataModel.RepliesModel info) {
        commitatPerson = data;

        show(info, data);
    }

    private class CustomWebViewClient extends WebViewClient {

        private boolean mLastLoadFailed = false;

        @Override
        public void onPageFinished(WebView webView, String url) {
            super.onPageFinished(webView, url);
            if (!mLastLoadFailed) {
                CustomActionWebView customActionWebView = (CustomActionWebView) webView;
                customActionWebView.linkJSInterface();

                //进行评论加载
            }
        }

        @Override
        public void onPageStarted(WebView webView, String url, Bitmap favicon) {
            super.onPageStarted(webView, url, favicon);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            mLastLoadFailed = true;

            //进行评论加载
        }
    }

    private void getCommentData() {
        initParameter();

        NewsDetailsEntity.DataBean dataBean = mNewsEntity.getData();

        mParams.put("articleId", dataBean.getArticleId());
        mParams.put("categoryId1", dataBean.getCategoryId1());
        mParams.put("userId", MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""));
        mParams.put("token", MySharedPreferencesMgr.getString(SpfUtils.USER_TOKEN, ""));
        mParams.put("plat", "android");
        mParams.put("ifa", BaseApp.getDeviceID(mContext));
        mParams.put("page", page);
        mParams.put("pageSize", 10);

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.TOPIC_DETAIL_COMMENT),
                AsRes.TOPIC_DETAIL_COMMENT, mParams, TopicDetailComentEntity.class);
    }


    private void show(final TopicDetailComentEntity.DataModelXX.CommentsModel.DataModel.RepliesModel repliesModel, final TopicDetailComentEntity.DataModelXX.CommentsModel.DataModel cap) {
        //设置固定的dialog
        final Dialog bottomDialog = new Dialog(mContext, R.style.BottomDialog);

        View contentView = LayoutInflater.from(mContext).inflate(R.layout.item_for_comment, null);
        bottomDialog.setContentView(contentView);

        final EditText tvContent = (EditText) contentView.findViewById(R.id.id_for_commit_content);
        displayplay(tvContent, repliesModel, cap);

        TextView tvCancel = (TextView) contentView.findViewById(R.id.id_for_cancel);
        tvCancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //开启键盘，修复无法点击的Bug
                if (KeybordUtil.isSoftInputShow(TopsDetailsActivity.this)) {
                    KeybordUtil.closeKeybord(tvContent, mContext);
                }

                bottomDialog.dismiss();
            }
        });

        TextView tvCommit = (TextView) contentView.findViewById(R.id.id_for_commit);
        tvCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtil.isEmpty(MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""))) {
                    showToast(R.string.user_userid_null);

                    Intent loginIntent = new Intent(mContext, LoginActivity.class);
                    startActivity(loginIntent);
                    appFinish();
                    return;
                }

                //开启键盘，修复无法点击的Bug
                if (KeybordUtil.isSoftInputShow(TopsDetailsActivity.this)) {
                    KeybordUtil.closeKeybord(tvContent, mContext);
                }

                bottomDialog.dismiss();

                //发表评论
                commitComment(tvContent, cap, repliesModel);
            }
        });


        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        contentView.setLayoutParams(layoutParams);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.setCancelable(true);
        bottomDialog.setCanceledOnTouchOutside(true);
        bottomDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                KeybordUtil.closeKeybord(tvContent, mContext);
                bottomDialog.dismiss();
            }
        });
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        bottomDialog.show();

        //开启键盘，修复无法点击的Bug
        KeybordUtil.openKeybord(tvContent, mContext);
    }

    private void displayplay(EditText tvContent, TopicDetailComentEntity.DataModelXX.CommentsModel.DataModel.RepliesModel repliesModel, TopicDetailComentEntity.DataModelXX.CommentsModel.DataModel cap) {
        if (repliesModel != null) {
            tvContent.setText("@" + repliesModel.getUserName() + " ");
            tvContent.setSelection(tvContent.getText().toString().length());
            return;
        }

        if (cap != null) {
            tvContent.setText("@" + cap.getComment().getUserName() + " ");
            tvContent.setSelection(tvContent.getText().toString().length());
            return;
        }
    }

    private void commitComment(EditText content, TopicDetailComentEntity.DataModelXX.CommentsModel.DataModel cp, TopicDetailComentEntity.DataModelXX.CommentsModel.DataModel.RepliesModel repliesModel) {
        if (mNewsEntity == null) {
            return;
        }

        loadingDialog = new DialogUtil().showGifdialog(mContext);
        loadingDialog.show();

        String type = cp == null ? "1" : "2";
        String c = content.getText().toString().trim();

        initParameter();
        mParams.put("type", type);

        if ("1".equalsIgnoreCase(type)) {
            mParams.put("articleId", mNewsEntity.getData().getArticleId());//文章ID，主评论(type=1)时必填
            mParams.put("categoryId1", mNewsEntity.getData().getCategoryId1());//一级类目Id，主评论(type=1)时必填
        }

        if ("2".equalsIgnoreCase(type)) {
            if (repliesModel == null) {
                mParams.put("rootCommentId", commitatPerson.getComment().getCommentId());//回复的主评论Id，回复评论(type=2)时必填
                mParams.put("userIdReplied", commitatPerson.getComment().getUserId());//回复的评论的用户Id，回复评论(type=2)时必填

                c = c.replace("@" + commitatPerson.getComment().getUserName() + " ", "");
            } else {
                mParams.put("rootCommentId", repliesModel.getRootCommentId());//回复的主评论Id，回复评论(type=2)时必填
                mParams.put("userIdReplied", repliesModel.getUserId());//回复的评论的用户Id，回复评论(type=2)时必填

                c = c.replace("@" + repliesModel.getUserName() + " ", "");
            }
        }

        mParams.put("userId", MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""));
        mParams.put("token", MySharedPreferencesMgr.getString(SpfUtils.USER_TOKEN, ""));
        mParams.put("plat", "android");
        mParams.put("ifa", BaseApp.getDeviceID(mContext));
        mParams.put("commentText", c);

        //清空输入框
        content.setText("");
        mTopicDetailComment.setText("");
        commitatPerson = null;

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.TOPIC_COMMIT_COMMENT),
                AsRes.TOPIC_COMMIT_COMMENT, mParams, CommentCommitEntity.class);
    }

}